#!/bin/bash


FILE=$1
BC_SCALE=5

NUMBER_OF_FILES=`cat $FILE | egrep -x "File = .+" | sort | uniq | wc -l`

FILES_COUNT=0

CURRENT_FILE_INDEX=none

let LAST_FILE=$NUMBER_OF_FILES-1

for THE_FILE in $(seq 0 $LAST_FILE)
do
	let INDEX=$THE_FILE
	COUNT[$INDEX]=0
	SUM[$INDEX]=0
done

function contains() {
    local n=$#
    local value=${!n}
    for ((i=0;i < $#;i++)) {
        if [ "${!i}" == "${value}" ]; then
            echo "y"
                let i--
            return $i
        fi
    }
    echo "n"
    return 0
}



while read line
do

        if [[ "$line" =~ ^"File = ".+$ ]]
        then
                FILE=`echo $line | cut -d " " -f 3`

                CONTAINS=$(contains "${FILES[@]}" "$FILE")
                INDEX=$?

                if [[ $CONTAINS == "n" ]]
                then
                        FILES[$FILES_COUNT]=$FILE
                        CURRENT_FILE_INDEX=$FILES_COUNT
                        let FILES_COUNT++
                else

                        CURRENT_FILE_INDEX=$INDEX

                fi


        fi

	if [[ "$line" =~ ^"Formula has "[0-9]+" variables and "[0-9]+" clauses"$ ]]
	then
		VAR=`echo $line | cut -d " " -f 3`
		CLA=`echo $line | cut -d " " -f 6`

		VARIABLES[$CURRENT_FILE_INDEX]=$VAR
		CLAUSES[$CURRENT_FILE_INDEX]=$CLA

	fi

	if [[ "$line" == "SATISFIABLE" ]] || [[ "$line" == "UNSATISFIABLE" ]] || [[ "$line" == "UNDEF" ]]
	then
		STATS=`echo $line | sed s/"ISFIABLE"//g`
		SAT_STATUS[$CURRENT_FILE_INDEX]=$STATS
	fi

	if [[ "$line" =~  ^[0-9]+("."[0-9]*)?"user "[0-9]+("."[0-9]*)?"system "([0-9]+":")?[0-9]+":"[0-9]+("."[0-9]*)?"elapsed" ]]
	then

		CURRENT_VALUE=$line

		if [[ "$line" =~  ^[0-9]+("."[0-9]*)?"user "[0-9]+("."[0-9]*)?"system "[0-9]+":"[0-9]+":"[0-9]+("."[0-9]*)?"elapsed" ]]
		then
			CURRENT_VALUE=`echo "$line" | cut -d " " -f 3 | cut -d "e" -f 1 | sed s/:/*3600+/1`

		fi

		CURRENT_VALUE=`echo "$CURRENT_VALUE" | cut -d " " -f 3 | cut -d "e" -f 1 | sed s/:/*60+/g`
		CURRENT_VALUE=`echo "scale = $BC_SCALE; $CURRENT_VALUE" | bc`

		let INDEX=${CURRENT_FILE_INDEX}

		let COUNT[$INDEX]++
		SUM[$INDEX]=`echo "scale = ${BC_SCALE}; $CURRENT_VALUE + ${SUM[$INDEX]}" | bc`

	fi

done < $FILE

for THE_FILE in $(seq 0 $LAST_FILE)
do
	let INDEX=$THE_FILE
        if [ "${COUNT[$INDEX]}" -ne "0" ]
        then
	        echo "File = ${FILES[$THE_FILE]}"
		echo "Variables = ${VARIABLES[$THE_FILE]}"
		echo "Clauses = ${CLAUSES[$THE_FILE]}"
		echo "Status = ${SAT_STATUS[$THE_FILE]}"
                AVERAGE=`echo "scale = $BC_SCALE; ${SUM[$INDEX]}/${COUNT[$INDEX]}" | bc`
                echo -e "Average = "$AVERAGE
	        echo -e "Count = "${COUNT[$INDEX]}

       	fi
done
